
using System;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Configuration;

namespace Hook
{
	class Do
	{

		static void Main(string[] args)
		{
			ServiceBase[] MyServices;
			MyServices = new ServiceBase[] { new MyService() };
			System.ServiceProcess.ServiceBase.Run(MyServices);
		}
		
	}

	public class MyService : ServiceBase
	{
		private Thread t 	= null;
		private Command cmd = null;

		public MyService()
		{
			cmd = new Command();
		}

		protected override void OnStart(string[] args)
		{
			t = new Thread(new ThreadStart(ThreadProc));
			t.Start();
		}

		protected override void OnStop()
		{
			if(t.IsAlive) t.Abort();
		}

		public void ThreadProc()
		{
			int i = 0;
			string lockPath 	= System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "lock";
			string logPath 		= System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log";
			string errorPath 	= System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "error";
			File.AppendAllText(logPath, DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + " 线程已启动" + Environment.NewLine);
			while(true)
			{
				if(File.Exists(lockPath))
				{
					string gitPath = File.ReadAllText(lockPath).ToString();
					string time = DateTime.Now.ToString("yy-MM-dd HH:mm:ss");
					if(Directory.Exists(gitPath))
					{
						string res = cmd.RunCmd(new string[]{"cd "+ gitPath +" && "+ gitPath.Substring(0, 1) +": && git pull 2>&1"});
						File.AppendAllText(logPath, time + " " + res + Environment.NewLine);
					}
					else
					{
						File.AppendAllText(logPath, time + " 要拉取的项目目录不存在" + Environment.NewLine);
					}
					File.Delete(lockPath);
				}
				Console.WriteLine("{0}", i++);
				Thread.Sleep(1000);
			}
		}
	}

	[System.ComponentModel.RunInstallerAttribute(true)]
	public class MyInstaller : System.Configuration.Install.Installer
    { 
        private System.ServiceProcess.ServiceProcessInstaller spInstaller;  
        private System.ServiceProcess.ServiceInstaller sInstaller;  
        private System.ComponentModel.IContainer components = null;  
  
        public MyInstaller()
		{
			InitializeComponent();
		}
		
        protected override void Dispose(bool disposing)  
        {  
            if (disposing && (components != null))  
            {  
                components.Dispose();  
            }  
            base.Dispose(disposing);  
        }  
 
        private void InitializeComponent()  
        {  
              
            components = new System.ComponentModel.Container();  
  
            // 创建ServiceProcessInstaller对象和ServiceInstaller对象  
            this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();  
            this.sInstaller = new System.ServiceProcess.ServiceInstaller();  
  
            // 设定ServiceProcessInstaller对象的帐号、用户名和密码等信息  
            this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;  
            this.spInstaller.Username = null;  
            this.spInstaller.Password = null;  
  
            // 设定服务名称  
            this.sInstaller.ServiceName = "GitHookService";
            this.sInstaller.DisplayName = "GitHookService";
  
            // 设定服务的启动方式  
            this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;  
  
            this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.spInstaller, this.sInstaller });  
        }
	}

	public class Command{
		private Process proc = null;
		public Command()
		{
			proc = new Process();
		}

		public string RunCmd(string[] cmds) 
		{
			string output = "";
			try {
				proc.StartInfo.CreateNoWindow = true;
				proc.StartInfo.FileName = "cmd.exe";
				proc.StartInfo.UseShellExecute = false;
				proc.StartInfo.RedirectStandardError = true;
				proc.StartInfo.RedirectStandardInput = true;
				proc.StartInfo.RedirectStandardOutput = true;
				proc.Start();
				foreach(string cmd in cmds)
				{
					proc.StandardInput.WriteLine(cmd);
				}
				proc.StandardInput.WriteLine("exit");

				output = proc.StandardOutput.ReadToEnd();
				proc.Close();
			} catch {
				output = "执行 CMD 出错啦";
			}
			
			return output;
		}

		public string RunCmd(string cmd) 
		{
			return RunCmd(new string[]{cmd});
		}
	}
}
